package bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Dgg
 * @Date: 2021/11/21 21:47
 */
@Slf4j
public class BioServer {
	//注意main 方法在会被阻塞 并且 拿到数据过后会走一遍循环 又被阻塞了
	public static void main(String[] args) throws IOException {

		ExecutorService executorService = Executors.newCachedThreadPool();

		//创建serverSocket
		ServerSocket serverSocket = new ServerSocket(5555);
		log.debug("---服务端启动----");

		while (true) {
			System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
			//监听，等待客户端链接
			final Socket accept = serverSocket.accept();
			log.debug("----连接到一个客户端----");
			//创建一个线程和客户端通讯
			executorService.execute(new Runnable() {
				@Override
				public void run() {

					//可以和客户端通讯
					handlerSocket(accept);
				}
			});
		}
	}

	public static void handlerSocket(Socket socket) {
		byte[] bytes = new byte[1024];
		//通过socket 获取输入流
		try {
			log.debug("线程信息： id ==== " + Thread.currentThread().getId() + "==名称:" + Thread.currentThread().getName());
			InputStream inputStream = socket.getInputStream();

			//循环读取客户端发送的数据
			while (true) {
				System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
				int read = inputStream.read(bytes);
				if (read != -1) {
					//输出客户端发送的数据
					System.out.println(new String(bytes, 0, read));//输出客户端发送的数据
				} else {
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
